package offer2;

import java.util.concurrent.locks.ReentrantLock;

public class AQSDemo {
    /*
    AQS：AbstractQueuedSynchronizer（抽象的队列同步器）
    线程阻塞机制：排队等候机制
    int变量：state状态，0代表无线程占用，1代表有线程占用
    CLH队列：双向队列，里面有Node节点存储Thread
    Node类：头指针，尾指针，前指针，后指针，waitStatus（每个线程排队的状态）

    ReentrantLock的公平锁和非公平锁的区别就在于hasQueuedPredecessors方法，这个方法判断了是否需要排队

        public final boolean hasQueuedPredecessors() {
        // The correctness of this depends on head being initialized
        // before tail and on head.next being accurate if the current
        // thread is first in queue.
        Node t = tail; // Read fields in reverse initialization order
        Node h = head;
        Node s;
        return h != t &&
            ((s = h.next) == null || s.thread != Thread.currentThread());
    }

        protected final boolean tryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {
            if (!hasQueuedPredecessors() &&
                compareAndSetState(0, acquires)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        else if (current == getExclusiveOwnerThread()) {
            int nextc = c + acquires;
            if (nextc < 0)
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
        }
        return false;
    }
    */

    ReentrantLock lock = new ReentrantLock(true);

}
